package com.violet.interceptors;


import com.violet.utils.JwtTokenUtil;
import com.violet.utils.UserContent;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class ManagerAdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是登录请求，则放行
        if (request.getRequestURI().equals("/manager/admin/login")) {
            return true;
        }
        // 获取 Token，如果没有或者 Token 无效，则返回错误信息
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);
            return false;
        } else {
            try {
                Claims claims = JwtTokenUtil.parseToken(token);
                String string = (String) claims.get("userId");
                UserContent.setUserId(string);
                return true;
            } catch (Exception e) {
                response.setStatus(401);
                return false;
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContent.removeUserId();
    }
}
